package com.rdgk.newtech.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rdgk.newtech.dao.FileDao;
import com.rdgk.newtech.service.FileService;
import com.rdgk.newtech.util.CommonUtil;
import com.rdgk.newtech.util.PropertiesConfig;
import com.rdgk.newtech.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * 附件表
 */
@Service
public class FileServiceImpl implements FileService {

	@Autowired
	private FileDao dao;
	@Autowired
	private PropertiesConfig config;
	/**
	 * 新增附件
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public JSONObject addFile(HttpServletRequest request) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		JSONObject jsonObject = CommonUtil.request2Json(request);
		jsonObject.put("createdate",df.format(new Date()));
		dao.addFile(jsonObject);
		JSONObject result = CommonUtil.successJson(jsonObject);
		return result;
	}

	/**
	 * 全部文章列表
	 */
	@Override
	public JSONObject listFile(JSONObject jsonObject) {
		CommonUtil.fillPageParam(jsonObject);
		int count = dao.countFile(jsonObject);
		List<JSONObject> list = dao.listFile(jsonObject);
		return CommonUtil.successPage(jsonObject, list, count);
	}


	/**
	 * 删除文章
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public JSONObject deleteFileById(JSONObject jsonObject) {
		dao.deleteFileById(jsonObject);
		return CommonUtil.successJson();
	}

	/**
	 * 新增附件
	 */
	@Override

	@Transactional(rollbackFor = Exception.class)
	public JSONObject uploadFile(HttpServletRequest request, MultipartFile file) {
		JSONObject jsonObject = UploadFileUtil.uploadFile(request,file,config.getUploadPath());
		JSONObject result = CommonUtil.successJson(jsonObject);
		return result;
	}
}
